package com.lanlian.cayman.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lanlian.cayman.BuildConfig;
import com.lanlian.cayman.LLApplication;
import com.lanlian.cayman.R;
import com.lanlian.cayman.activity.AboutActivity;
import com.lanlian.cayman.activity.BankActivity;
import com.lanlian.cayman.activity.FundAccountActivity;
import com.lanlian.cayman.activity.LoginActivity;
import com.lanlian.cayman.activity.MessageActivity;
import com.lanlian.cayman.activity.MineIndexActivity;
import com.lanlian.cayman.activity.ProfitLossDetailsActivity;
import com.lanlian.cayman.activity.QuestionActivity;
import com.lanlian.cayman.activity.RechargeActivity;
import com.lanlian.cayman.activity.RiskStateActivity;
import com.lanlian.cayman.activity.SettingActivity;
import com.lanlian.cayman.activity.TradeDetailsDealActivity;
import com.lanlian.cayman.activity.TradeDetailsEntrustActivity;
import com.lanlian.cayman.activity.TradeDetailsFundActivity;
import com.lanlian.cayman.activity.UpdateRegisterAgreementActivity;
import com.lanlian.cayman.activity.VerifyMobileActivity;
import com.lanlian.cayman.activity.WithdrawActivity;
import com.lanlian.cayman.utils.VolleyRequestUtils;
import com.lanlian.cayman.view.RiskInvestigationDialog;
import com.lanlian.commonlib.base.BaseFragment;
import com.lanlian.commonlib.bean.BaseResponse;
import com.lanlian.commonlib.bean.ReqUserInfo;
import com.lanlian.commonlib.bean.RespUserLogin;
import com.lanlian.commonlib.bean.db.DBMessage;
import com.lanlian.commonlib.bean.db.DBUser;
import com.lanlian.commonlib.common.SystemConfig;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.network.INetWorkCallback;
import com.lanlian.commonlib.util.EventBusUtils;
import com.lanlian.commonlib.util.OnEventID;
import com.lanlian.commonlib.util.OnEventUtils;
import com.lanlian.uikit.ActionItem;
import com.lanlian.uikit.CustomBottomSheetDialog;
import com.lanlian.uikit.CustomDialog;
import com.scwang.smartrefresh.header.BezierCircleHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : xiaobo.hu@foxtry.com
 *     date   : 2018/8/9 13:40
 *     desc   : 我的TAB
 *     version: 1.0
 * </pre>
 */
public class MineFragment extends BaseFragment implements View.OnClickListener {

    private SmartRefreshLayout mLayRefresh;
    private RelativeLayout mLayLogin;
    private ImageView mImgSetting;
    private ImageView mImgSetting2;
    private TextView mTvUserName;
    private TextView mTvUserId;
    private TextView mTvDocumentaryId;
    private RelativeLayout mLayNoLogin;
    private TextView mTvAvailableFunds;
    private TextView mTvDynamicProfit;
    private TextView mTvYesterdaySettlement;
    private TextView mTvDealRecord;
    private TextView mTvEntrustmentDetail;
    private TextView mTvPnlDetails;
    private TextView mTvCapitalFlow;
    private TextView mTvRecharge;
    private TextView mTvWithdraw;
    private TextView mTvMessageCenter;
    private TextView mTvPoint;
    private TextView mTvQuestion;
    private TextView mTvAbout;
    private LinearLayout mLayAccount;
    private LinearLayout mLayCash;
    private LinearLayout mLayDetails;
    private TextView mTvChange;
    private LinearLayout mLayNoLoginOperate;
    private TextView mTvBank;
    private TextView mTvRiskInvestigation2;
    private TextView mTvAccountQuery;
    private TextView mTvRiskInvestigation;
    private TextView mTvUpload;
    private TextView mTvAuthentication;
    private TextView mTvUpdateAccountInfo;
    private View mView1;
    private View mView2;
    private View mView3;
    private boolean mIsUIVisible;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, null);
        mIsUIVisible = true;
        initView(view);
        setListeners();
        setLoginLayout();
//        mTvChange.setVisibility(View.GONE);
        mTvChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomBottomSheetDialog dialog = new CustomBottomSheetDialog(getActivity(), "打包时间：" + BuildConfig.releaseTime);
                dialog.addAction(new ActionItem("开曼线上环境", SystemConfig.getHomeEnvironment() == SystemConfig.CAYMAN_ONLINE
                        ? R.color.color_T7 : 0));
                dialog.addAction(new ActionItem("开曼测试环境", SystemConfig.getHomeEnvironment() == SystemConfig.CAYMAN_QA
                        ? R.color.color_T7 : 0));
                dialog.setOnItemClickListener(new CustomBottomSheetDialog.OnItemOnClickListener() {
                    @Override
                    public void onItemClick(ActionItem item, int position) {
                        switch (position) {
                            case 0:
                                SystemConfig.setHomeEnvironment(SystemConfig.CAYMAN_ONLINE);
                                break;
                            case 1:
                                SystemConfig.setHomeEnvironment(SystemConfig.CAYMAN_QA);
                                break;
                            default:
                                break;
                        }
                        EventBusUtils.post(new EventMessage(EventCode.EVENT_COLOR_TOPIC_CHANGE));
                    }
                });
                dialog.showDialog();
            }
        });
        return view;
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        mLayAccount = view.findViewById(R.id.lay_account);
        mLayRefresh = view.findViewById(R.id.lay_refresh);
        mLayLogin = view.findViewById(R.id.lay_login);
        mImgSetting = view.findViewById(R.id.img_setting);
        mImgSetting2 = view.findViewById(R.id.img_setting2);
        mTvUserName = view.findViewById(R.id.tv_user_name);
        mTvUserId = view.findViewById(R.id.tv_user_id);
        mTvDocumentaryId = view.findViewById(R.id.tv_documentary_id);
        mLayNoLogin = view.findViewById(R.id.lay_no_login);
        mTvAvailableFunds = view.findViewById(R.id.tv_available_funds);
        mTvDynamicProfit = view.findViewById(R.id.tv_dynamic_profit);
        mTvYesterdaySettlement = view.findViewById(R.id.tv_yesterday_settlement);
        mTvDealRecord = view.findViewById(R.id.tv_deal_record);
        mTvEntrustmentDetail = view.findViewById(R.id.tv_entrustment_detail);
        mTvPnlDetails = view.findViewById(R.id.tv_pnl_details);
        mTvCapitalFlow = view.findViewById(R.id.tv_capital_flow);
        mTvRecharge = view.findViewById(R.id.tv_recharge);
        mTvWithdraw = view.findViewById(R.id.tv_withdraw);
        mTvMessageCenter = view.findViewById(R.id.tv_message_center);
        mTvPoint = view.findViewById(R.id.tv_point);
        mTvQuestion = view.findViewById(R.id.tv_question);
        mTvAbout = view.findViewById(R.id.tv_about);
        mLayCash = view.findViewById(R.id.lay_cash);
        mLayDetails = view.findViewById(R.id.lay_details);
        mTvChange = view.findViewById(R.id.tv_exchange);
        mLayNoLoginOperate = view.findViewById(R.id.lay_no_login_operate);
        mTvBank = view.findViewById(R.id.tv_bank);
        mTvRiskInvestigation2 = view.findViewById(R.id.tv_risk_investigation2);
        mTvAccountQuery = view.findViewById(R.id.tv_account_query);
        mTvRiskInvestigation = view.findViewById(R.id.tv_risk_investigation);
        mTvUpload = view.findViewById(R.id.tv_upload);
        mTvAuthentication = view.findViewById(R.id.tv_authentication);
        mView1 = view.findViewById(R.id.view1);
        mTvUpdateAccountInfo = view.findViewById(R.id.tv_update_account_info);
        mView3 = view.findViewById(R.id.view3);
        mView2 = view.findViewById(R.id.view2);
        mLayRefresh.setRefreshHeader(new BezierCircleHeader(getActivity()));
        mLayRefresh.setPrimaryColorsId(R.color.color_B1, R.color.color_K4);
    }

    @Override
    protected void setListeners() {
        super.setListeners();
        mTvUserName.setOnClickListener(this);
        mLayNoLogin.setOnClickListener(this);
        mTvAbout.setOnClickListener(this);
        mTvQuestion.setOnClickListener(this);
        mTvMessageCenter.setOnClickListener(this);
        mTvRecharge.setOnClickListener(this);
        mTvWithdraw.setOnClickListener(this);
        mTvDealRecord.setOnClickListener(this);
        mTvPnlDetails.setOnClickListener(this);
        mTvEntrustmentDetail.setOnClickListener(this);
        mTvCapitalFlow.setOnClickListener(this);
        mLayAccount.setOnClickListener(this);
        mTvBank.setOnClickListener(this);
        mTvRiskInvestigation.setOnClickListener(this);
        mTvRiskInvestigation2.setOnClickListener(this);
        mTvAccountQuery.setOnClickListener(this);
        mTvUpload.setOnClickListener(this);
        mTvAuthentication.setOnClickListener(this);
        mImgSetting2.setOnClickListener(this);
        mImgSetting.setOnClickListener(this);
        mTvUpdateAccountInfo.setOnClickListener(this);
        mLayRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (mDBManager.isLogined()) {
                    EventBusUtils.post(new EventMessage(EventCode.EVENT_FUNDS_REFRESH));
                    getUserInfo();
                } else {
                    refreshLayout.finishRefresh();
                }
            }
        });
    }

    /**
     * 设置登录与未登录的布局
     */
    private void setLoginLayout() {
        if (mDBManager.isLogined()) {
            mLayNoLogin.setVisibility(View.GONE);
            mLayLogin.setVisibility(View.VISIBLE);
            mLayAccount.setVisibility(View.VISIBLE);
            mLayDetails.setVisibility(View.VISIBLE);
            mLayCash.setVisibility(View.VISIBLE);
            if (mDBManager.getIsOldUser() == 0) {
                mTvUpdateAccountInfo.setVisibility(View.GONE);
                mView3.setVisibility(View.GONE);
            } else {
                mTvUpdateAccountInfo.setVisibility(View.VISIBLE);
                mView3.setVisibility(View.VISIBLE);
            }
            mTvRiskInvestigation2.setVisibility(View.VISIBLE);
            mTvBank.setVisibility(View.VISIBLE);
            mView1.setVisibility(View.VISIBLE);
            mView2.setVisibility(View.VISIBLE);
            mLayNoLoginOperate.setVisibility(View.GONE);
            setUserInfo();
        } else {
            mLayNoLogin.setVisibility(View.VISIBLE);
            mLayLogin.setVisibility(View.GONE);
            mLayAccount.setVisibility(View.GONE);
            mLayDetails.setVisibility(View.GONE);
            mLayCash.setVisibility(View.GONE);
            mTvRiskInvestigation2.setVisibility(View.GONE);
            mTvUpdateAccountInfo.setVisibility(View.GONE);
            mView3.setVisibility(View.GONE);
            mLayNoLoginOperate.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 获取用户信息
     */
    private void getUserInfo() {
        VolleyRequestUtils.getInstance().getUserInfo(this.toString(), new ReqUserInfo(), new INetWorkCallback() {
            @Override
            public void onSuccess(Object response) {
                mLayRefresh.finishRefresh();
                RespUserLogin respUserLogin = (RespUserLogin) response;
                respUserLogin.setToken(mDBManager.getToken());
                if (mDBManager.saveUser(respUserLogin)) {
                    setLoginLayout();
                }
            }

            @Override
            public void onFail(BaseResponse baseResponse) {
                mLayRefresh.finishRefresh();
            }
        });
    }

    /**
     * 设置用户信息
     */
    private void setUserInfo() {
        DBUser dbUser = mDBManager.getUser();
        if (dbUser != null) {
            if (TextUtils.isEmpty(dbUser.getUserName())) {
                mTvUserName.setText(dbUser.getRealName());
            } else {
                mTvUserName.setText(dbUser.getUserName());
            }
            mTvUserId.setText(String.format("账号：%s", dbUser.getAccountNo()));
            mTvDocumentaryId.setText(String.format("跟单编号：%d", dbUser.getNo()));
        }
        setFunds();
        setMessagePoint();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.tv_about:
                OnEventUtils.onEvent(getActivity(), OnEventID.ABOUT_LION);
                startActivity(new Intent(getActivity(), AboutActivity.class));
                break;
            case R.id.tv_question:
                OnEventUtils.onEvent(getActivity(), OnEventID.COMMON_QUESTION);
                startActivity(new Intent(getActivity(), QuestionActivity.class));
                break;
            case R.id.tv_message_center:
                if (mDBManager.isLogined()) {
                    OnEventUtils.onEvent(getActivity(), OnEventID.MESSAGE_CENTER);
                    startActivity(new Intent(getActivity(), MessageActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                break;
            case R.id.tv_user_name:
                startActivity(new Intent(getActivity(), MineIndexActivity.class));
                break;
            case R.id.lay_no_login:
                startActivity(new Intent(getActivity(), LoginActivity.class));
                break;
            case R.id.lay_account:
                OnEventUtils.onEvent(getActivity(), OnEventID.ACCOUNT);
                startActivity(new Intent(getActivity(), FundAccountActivity.class));
                break;
            case R.id.tv_deal_record:
                OnEventUtils.onEvent(getActivity(), OnEventID.DEAL_DETAIL);
                startActivity(new Intent(getActivity(), TradeDetailsDealActivity.class));
                break;
            case R.id.tv_entrustment_detail:
                OnEventUtils.onEvent(getActivity(), OnEventID.ENTRUST_DETAIL);
                startActivity(new Intent(getActivity(), TradeDetailsEntrustActivity.class));
                break;
            case R.id.tv_pnl_details:
                OnEventUtils.onEvent(getActivity(), OnEventID.STOP_PNL_DETAIL);
                startActivity(new Intent(getActivity(), ProfitLossDetailsActivity.class));
                break;
            case R.id.tv_capital_flow:
                OnEventUtils.onEvent(getActivity(), OnEventID.CAPITAL_FLOW);
                startActivity(new Intent(getActivity(), TradeDetailsFundActivity.class));
                break;
            case R.id.tv_withdraw:
                startActivity(new Intent(getActivity(), WithdrawActivity.class));
                break;
            case R.id.tv_recharge:
                startActivity(new Intent(getActivity(), RechargeActivity.class));
                break;
            case R.id.tv_bank:
                startActivity(new Intent(getActivity(), BankActivity.class));
                break;
            case R.id.tv_account_query:
                startActivity(new Intent(getActivity(), VerifyMobileActivity.class)
                        .putExtra("operateId", 1));
                break;
            case R.id.tv_upload:
                startActivity(new Intent(getActivity(), VerifyMobileActivity.class)
                        .putExtra("operateId", 3));
                break;
            case R.id.tv_authentication:
                startActivity(new Intent(getActivity(), VerifyMobileActivity.class)
                        .putExtra("operateId", 4));
                break;
            case R.id.tv_risk_investigation:
                startActivity(new Intent(getActivity(), VerifyMobileActivity.class)
                        .putExtra("operateId", 2));
                break;
            case R.id.tv_risk_investigation2:
                startActivity(new Intent(getActivity(), RiskStateActivity.class)
                        .putExtra("mobile", mDBManager.getUser().getMobileNo()));
                break;
            case R.id.img_setting:
            case R.id.img_setting2:
                startActivity(new Intent(getActivity(), SettingActivity.class));
                break;
            case R.id.tv_update_account_info:
                startActivity(new Intent(getActivity(), UpdateRegisterAgreementActivity.class)
                        .putExtra("mobile", mDBManager.getUser().getMobileNo()));
                break;
            default:
                break;
        }
    }

    private void setFunds() {
        mTvYesterdaySettlement.setText(String.format("$ %.2f", LLApplication.getBeginCash()));
        mTvAvailableFunds.setText(String.format("$ %.2f", LLApplication.getAvailableFunds()));
        mTvDynamicProfit.setText(String.format("$ %.2f", LLApplication.getDynamicPnl()));
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        mIsUIVisible = !hidden;
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        super.onReceiveEvent(event);
        switch (event.getCode()) {
            case EventCode.EVENT_LOGIN_REFRESH:
                setLoginLayout();
                if (mIsUIVisible) {
                    if (mDBManager.getIsOldUser() == 1) {
                        new CustomDialog(getActivity(), new CustomDialog.OnClickListener() {
                            @Override
                            public void onLeftClick() {
                            }

                            @Override
                            public void onRightClick() {
                                startActivity(new Intent(getActivity(), UpdateRegisterAgreementActivity.class)
                                        .putExtra("mobile", mDBManager.getUser().getMobileNo()));
                            }
                        }).setContent("尊敬的客户，为了给您提供更完善的交易服务，请您完善账户资料补充申请（通讯地址、资产职业信息），感谢您的配合！")
                                .setLeft("稍后").setRight("进入").setGravity(Gravity.LEFT).show();
                    } else if (mDBManager.getUser().getRiskAuthState() == 0) {
                        new RiskInvestigationDialog(getActivity(), new RiskInvestigationDialog.OnClickListener() {
                            @Override
                            public void onWriteClick() {
                                startActivity(new Intent(getActivity(), RiskStateActivity.class)
                                        .putExtra("mobile", mDBManager.getUser().getMobileNo()));
                            }

                            @Override
                            public void onCloseClick() {
                            }
                        }).show();
                    }
                }
                break;
            case EventCode.EVENT_LOGIN_OUT_REFRESH:
                setLoginLayout();
                break;
            case EventCode.EVENT_MARKET:
                setFunds();
                break;
            case EventCode.EVENT_FUNDS_REFRESH:
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        setFunds();
                    }
                }, 3000);
                break;
            case EventCode.EVENT_MESSAGE_POINT:
                setMessagePoint();
                break;
            default:
                break;
        }
    }

    private void setMessagePoint() {
        boolean flag = false;
        for (DBMessage dbMessage : mDBManager.getMessageList()) {
            if (dbMessage.getIsRead() == 0) {
                flag = true;
                break;
            }
        }
        mTvPoint.setVisibility(flag ? View.VISIBLE : View.GONE);
    }

}
